﻿using System;
using System.Collections.Generic;
using System.Text;

namespace AutoUpdateService.Server
{
    using DotNetty.Buffers;
    using DotNetty.Transport.Channels;
    using AutoUpdateService.Mgr;
    using AutoUpdateService.Mgr.Model;
    using System.Net;

    public class ServerHandler : ChannelHandlerAdapter
    {
        private Server m_Server { set; get; } = null;

        public ServerHandler(Server server)
        {
            this.m_Server = server;
        }

        public override void ChannelActive(IChannelHandlerContext context)
        {
            ClientSession session = new ClientSession();

            session.channel = context.Channel;

            session.channelHashCode = session.channel.GetHashCode();

            session.ipAddress = context.Channel.RemoteAddress.ToString();

            Console.WriteLine(session.ipAddress);

            Mgr.ClientMgr.getInstance().addClient(session);

            Console.WriteLine("Active:" + context.Name);

            base.ChannelActive(context);

        }

        public override void ChannelRead(IChannelHandlerContext context, object message)
        {
            try
            {
                var byteBuffer = message as IByteBuffer;

                if (byteBuffer != null)
                {
                    Console.WriteLine("Client=>" + context.Channel.GetHashCode());

                    string msgString = byteBuffer.ToString(Encoding.UTF8);

                    //Console.WriteLine("Received from client=>" + msgString);

                    PacketMgr.getInstance().ProcessPacket(ClientMgr.getInstance().getClient(context.Channel.GetHashCode()), msgString);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }

            base.ChannelRead(context, message);
        }

        public override void ChannelInactive(IChannelHandlerContext context)
        {
            Mgr.ClientMgr.getInstance().removeClient(context.Channel.GetHashCode());

            Console.WriteLine("Inactive:" + context.Name);

            base.ChannelInactive(context);
        }

        public override void ExceptionCaught(IChannelHandlerContext context, Exception exception)
        {
            base.ExceptionCaught(context, exception);
        }
    }
}
